package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;

    @Override
    public Object getItemList(PageResult pageResult) {
        Page<Item> page = new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        String query = pageResult.getQuery();
        boolean flag = StringUtils.hasLength(query);
        queryWrapper.like(flag,"title", query);
        page = itemMapper.selectPage(page, queryWrapper);

        return pageResult.setTotal(page.getTotal()).setRows(page.getRecords());
    }

    @Override
    @Transactional
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void deleteItemById(Item item) {
        itemMapper.deleteById(item);
        itemDescMapper.deleteById(item);
    }

    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        Item item = itemVO.getItem();
        item.setStatus(true);
        itemMapper.insert(item);
        ItemDesc itemDesc = itemVO.getItemDesc();
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);
    }

    @Override
    @Transactional
    public void updateItem(Item item) {
        itemMapper.updateById(item);
    }

}
